<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle>
        <div style="margin: 10px">
          <div class="flex-container">
            <div style="display: inline-block; width: 200px; margin-left: 20px">
              <span>总二维码消耗：</span>
              <Progress :percent="(usageQuantity / number) * 100" :format="() => `${usageQuantity}/ ${number}`" />
            </div>
            <div style="display: inline-block; width: 200px; margin-left: 80px">
              <span>当前二维码消耗：</span>
              <Progress :percent="(count / number) * 100" :format="() => `${count}/${number}`" />
            </div>
            <div style="display: inline-block; width: 500px; margin-left: 80px">
              <span>分配控码数量：</span>
              <a-input-number v-model:value="formState.number" @pressEnter="submit" @change="change" :min="0"
                :max="remainingQuantity"></a-input-number>
              <a-button type="primary" style="margin-left: 10px;" @click="submit">生成</a-button>
              <a-button type="primary" style="margin-left: 10px;" preIcon="ant-design:export-outlined"
                @click="onExportXls"> 导出</a-button>
            </div>
          </div>
        </div>
      </template>
      <template #qrcodeRandom="{ record }">
        <QrCode :value="record.qrcodeUrl" :number="1" width="100" />
      </template>
      <template #href="{ record }">
        <span style="margin: 5px;" v-for="(item, index) in record.qrcodeManageControlList" :key="index"
          :copyable="{ text: item.randomCode }">{{ item.randomCode }}
          <!-- <TypographyText style="margin: 5px;" v-for="(item, index) in record.qrcodeManageControlList" :key="index"
            :copyable="{ text: item.rcode }">{{ item.rcode }}
          </TypographyText> -->
        </span>
      </template>
      <!--操作栏-->
      <!-- <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template> -->
    </BasicTable>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, unref, computed } from 'vue';
import { list, saveOrUpdate, getExportUrl } from './QrcodeManageControl.api';
import { useListPage } from '/@/hooks/system/useListPage';
import { BasicTable, TableAction } from '/@/components/Table';
import { QrCode } from '/@/components/Qrcode/index';
import { Typography, Progress, Modal } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import { defHttp } from '@/utils/http/axios';
import { useDebounceFn } from '@vueuse/core';
import { getImportUrl } from "@/views/system/user/user.api";
import { valid } from 'mockjs';

interface FormState {
  number: number;
}
const formState: UnwrapRef<FormState> = reactive({
  number: 0,
});

const total = ref<number>(0);
const count = ref<number>(0);
const number = ref('0');
const usageQuantity = ref('0');
const remainingQuantity = ref('0');
let timer = null; // 定时器
// 是否上次请求完毕
let requst = false;

const {
  query: { qmId },
} = useRoute();

const TypographyLink = Typography.Link;
const TypographyText = Typography.Text;
// 列表页面公共参数、方法
const { prefixCls, tableContext, onExportXls } = useListPage({
  designScope: 'qrcodemanagecontrol-template',
  tableProps: {
    // useSearchForm: false,
    showActionColumn: false,
    api: list,
    beforeFetch: (params) => {
      return Object.assign(params, { qmId: unref(qmId) });
    },
    afterFetch: () => {
      // 设置总数
      let rawDataSource = getRawDataSource();
      getCodeInfo(rawDataSource);
    },
    columns: [
      {
        title: '生成数量',
        align: 'center',
        width: 120,
        dataIndex: 'number',
      },
      {
        title: '生成时间',
        align: 'center',
        width: 180,
        dataIndex: 'createTime',
      },
      {
        title: '主码地址',
        align: 'center',
        dataIndex: 'url',
        width: 500,
        resizable: true,
      },
      {
        title: '随机码',
        align: 'center',
        dataIndex: 'qrcodeManageControlList',
        slots: { customRender: 'href' },
      },
    ],
    formConfig: {
      labelWidth: 40,
      actionColOptions: {
        xs: 24,
        sm: 8,
        md: 8,
        lg: 8,
        xl: 8,
        xxl: 8,
      },
    },
    actionColumn: {
      width: 150,
      fixed: 'right',
    },
  },
  exportConfig: {
    name: '随机码',
    url: getExportUrl,
    params: Object.assign({}, { qmId: unref(qmId) })
  },
});
const [registerTable, { reload, getRawDataSource }, { rowSelection, selectedRowKeys }] = tableContext;

// Emits声明
const emit = defineEmits(['register', 'success']);
//设置标题
const title = '二维码';

/**
 * 获取控码信息
 */
function getCodeInfo(rawDataSource) {
  // 获取控码信息
  defHttp.get({ url: '/qrcodeManageControl/queryControlCode' }).then((res) => {
    console.log(res);
    number.value = res.number;
    usageQuantity.value = res.usageQuantity;
    remainingQuantity.value = res.remainingQuantity;
    // 必须在最大之后执行，否则会截断
    total.value = rawDataSource.records.length ? rawDataSource.records[0].total : 0;
    count.value = total.value
  });
}
/**
 * 删除成功之后回调事件
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
 * 成功
 */
function success() {
  formState.number = 0;
  (selectedRowKeys.value = []) && reload();
}

/**
 * 操作栏
 */
function getTableAction(record) {
  const action = [];
  action.push({
    label: '导出',
  });
  return action;
}

function change() {
  count.value = parseInt(formState.number + total.value)
}

function submit() {
  Modal.confirm({
    content: '确认生成' + formState.number + '个二维码？',
    onOk: () => {
      saveOrUpdate({ qmId: qmId, number: parseInt(formState.number) }, false).then((res) => {
        console.log('请求成功：' + res);
        success();
      });
    }
  })
}
const reactiveMarks = computed(() => ({
  0: '0个',
  [unref(remainingQuantity)]: {
    style: {
      color: '#0051ff',
    },
    label: unref(remainingQuantity) + '个',
  },
}));
</script>

<style scoped>
.flex-container {
  display: flex;
}

/*update-begin---author:wangshuai ---date:20220705  for：查询组件input有后缀，隐藏掉------------*/
:deep(.ant-input-suffix) {
  display: none;
}

/*update-begin---author:wangshuai ---date:20220705  for：查询组件input有后缀，隐藏掉------------*/
</style>
